<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" 
    :showCancelBtn="true" :showOkBtn="true" :canFullscreen="false" :centered="true" :maskClosable="false"
    @ok="handleSubmit" width="500px"
  >
    <BasicForm @register="registerForm" :model="formModel"> 
      <template #tel="{ model, field }">
        <!-- 如果是组件需要进行双向绑定，model当前表单对象，field当前字段名称 
         :class="`${prefixCls}-input`" :value="innerValue" :disabled="disabled" v-bind="attrs" @change="onInputChange"
          <Avatar :size="60" v-if="avatarUrl" :src="avatarUrl" />
        -->
        <a-input v-model:value="model[field]" autocomplete="off" @change="fineCarelinerByTel(model, field)" :maxlength="11">
          <template #suffix>
            <Avatar :size="30" :src="avatarUrl" />
          </template>
        </a-input>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref, reactive } from 'vue';
  import { rules } from '/@/utils/helper/validator';
  import { defHttp } from '/@/utils/http/axios';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable, BasicColumn, TableImg } from '/@/components/Table';
  import { Tag, Avatar } from 'ant-design-vue';
  import { useForm } from '/@/components/Form/src/hooks/useForm';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { useLocaleStore } from '/@/store/modules/locale';
  import { useI18n } from '/@/hooks/web/useI18n';

  import BasicForm from '/@/components/Form/src/BasicForm.vue';

  const { userInfo } = useUserStore();
  const { t } = useI18n();
  // 声明Emits
  const emit = defineEmits(['register']);
  const $message = useMessage();
  const localeStore = useLocaleStore();
  
  const username  = ref('');
  const avatarUrl = ref('');
  // update-begin--author:liaozhiyang---date:20240124---for：【QQYUN-7970】国际化
  const title = ref(t('layout.header.dropdownItemSwitchAccount'));

  const formModel = reactive({
    openid: '',
    userid: '',
    memberId: '',
    headimgurl: '',
    skrName: '',
    skrTel: '',
    skrQrcode: '',
    skrWorkPic: ''
  });

  //表单配置
  const [registerForm, { resetFields, validate, setFieldsValue, clearValidate }] = useForm({
    schemas: [
      {
        label: 'openid',
        field: 'openid',
        component: 'Input',
        show: false,
      },
      {
        label: 'memberId',
        field: 'memberId',
        component: 'Input',
        show: false,
      },
      {
        label: '收客人姓名',
        field: 'skrName',
        component: 'Input',
        required: true,
        componentProps: {
          autocomplete: "off",
        },
      },
      {
        label: '收客人电话',
        field: 'skrTel',
        component: 'Input',
        slot: 'tel',
        componentProps: {
          autocomplete: "off",
        }, 
        dynamicRules: ({ model }) => {
          return [
            { required: true, message: '电话不能为空！' },
            { validator: (_, value) => {
              return new Promise((resolve, reject) => {
                //验证手机号是否正确
                let reg = /^1[3456789]\d{9}$/;
                if (!reg.test(value)) {
                  reject('请输入正确手机号！');
                }
                resolve();
              });
              },
            },
          ]
        },
      },
      {
        label: '微信二维码',
        field: 'skrQrcode',
        component: 'JImageUpload',
        required: true,
        componentProps: {
          autocomplete: "off",
        },
        colProps: { span: 12 },
      },
      {
        label: '收客人照片',
        field: 'skrWorkPic',
        component: 'JImageUpload',
        componentProps: {
          autocomplete: "off",
        },
        colProps: { span: 12 },
      },
    ],
    showActionButtonGroup: false,
    wrapperCol: { span: 18 },
    labelWidth: localeStore.getLocale == 'zh_CN' ? 100 : 160,
  });
  // update-end--author:liaozhiyang---date:20240124---for：【QQYUN-7970】国际化
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner();

  //表单提交事件
  async function fineCarelinerByTel(model, field) {
    try {
      if (!model || !field) {
        return 
      }

      let tel = model[field];
      if (!tel) {
        return 
      }

      if (tel.length != 11) {
        return
      }

      console.info("fineCarelinerByTel", tel)
      
      //提交表单
      let params = Object.assign({ tel: tel });
      defHttp.get({ url: '/careliner/getCarelinerByPhone', params }, { isTransformResponse: false }).then((res) => {
        console.info("formModel", res);
        if (res.success) {
          formModel.skrTel = tel;
          Object.assign(formModel, res.result);
          avatarUrl.value = formModel.headimgurl;
        } else {
          let obj = {
            headimgurl: '',
            openid: '',
            memberId: '',
            skrTel: tel,
          }
          Object.assign(formModel, obj);
          avatarUrl.value = "";
        }
        console.info(formModel)
        setFieldsValue({
          ...formModel
        });
        //formModel.skrWorkPic = 'http://www.yygj.vip/full/assets/header-1b5fa5f8.jpg'
      });
    } finally {

    }
  }

  //表单提交事件
  async function handleSubmit() {
    try {
      console.info("handleSubmit@");
      const values = await validate();
      setModalProps({ confirmLoading: true });
      let user = {
        userId: userInfo?.id,
      } 
      //提交表单
      let params = Object.assign(user, values);
      if (!params.memberId) {
        $message.createMessage.warn("当前电话未在懒熊旅行注册！");
        return
      }
      defHttp.put({ url: '/careliner/updateCareliner', params }, { isTransformResponse: false }).then((res) => {
        if (res.success) {
          $message.createMessage.success(res.message);
          //关闭弹窗
          closeModal();
        } else {
          $message.createMessage.warning(res.message);
        }
      });
    } catch (error) {
      console.info(error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  async function load() {
    let userid = userInfo?.id
    let params = { userid: userid }
    await defHttp.get({ url: '/careliner/getCarelinerByUserId', params }, { isTransformResponse: false }).then((res) => {
      if (res.success && res.result) {
        Object.assign(formModel, res.result);
        avatarUrl.value = formModel.headimgurl;
      } else {
        avatarUrl.value = '/logo2.png';
      }
      //console.info(formModel, res.result);
      //formModel.skrWorkPic = 'http://www.yygj.vip/full/assets/header-1b5fa5f8.jpg'
      setFieldsValue({
        ...formModel
      });
    });
  }

  async function show() {
    let name = userInfo?.realname
    if (!name) {
      $message.createMessage.warning('当前系统无登录用户!');
      return;
    } else {
      await setModalProps({ visible: true });
      await resetFields();
      await clearValidate();
      await load();
    }
  }

  defineExpose({
    title,
    show,
  });
</script>
